<?php
/**
 * @package Joomla
 * @subpackage Jmonoslideshow
 * @copyright (C) 2010 - Matthieu BARBE - www.ccomca.com
 * @license GNU/GPL v2
 * 
 * Jmonoslideshow is a Joomla extension for Monoslideshow.
 *
 * Jmonoslideshow uses :
 * Monoslideshow (http://www.monoslideshow.com/)
 * Plupload (http://www.plupload.com/) by Moxicode Systems
 * json class by Michal Migurski, Matt Knapp, Brett Stimmerman
 * jquery a JavaScript Library (http://jquery.com/)
 * getid3 library (http://getid3.sourceforge.net/)
 * swfobject is an easy-to-use and standards-friendly method to embed Flash content, which utilizes one small JavaScript file (http://code.google.com/p/swfobject/)
 * Chained Selects jQuery Plugin (http://www.appelsiini.net/2010/jquery-chained-selects)
 *
 * Jmonoslideshow is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import the Joomla modellist library
jimport('joomla.application.component.modellist');

// import the joomla language library
jimport('joomla.language.helper');


/**
 * Monoslideshow Model
 *
 * @package    Monoslideshow
 * @subpackage Models
 */
class JmonoslideshowModelMedias extends JModelList
{
	/**
	 * @var		array	 The authorized ordering fields.
	 *
	 * @since	0.0.1
	 *
	 * @see		JModelList::$filter_fields
	 */
	protected $filter_fields = array('title', 'published', 'rel.ordering', 'id', 'author', 'created');

	/**
	 * Constructor.
	 *
	 * @param	array	$config An optional associative array of configuration settings.
	 *
	 * @since	0.0.1
	 *
	 * @see		JModelList::__construct
	 */
	public function __construct($config = array()) 
	{
		parent::__construct($config);

		
	}

/**
	 * Method to auto-populate the model state.
	 *
	 * @param	string	$ordering	An optional ordering field.
	 * @param	string	$direction	An optional direction (asc|desc).
	 *
	 * @return void
	 *
	 * @note	List of internal states
	 *			- filter.search			title to search for
	 *			- filter.access			array of access levels for filtering
	 *			- filter.published		array of states for filtering
	 *			- filter.category_id	array of catid for filtering
	 *			- filter.language		array of language code for filtering
	 *			- list.limit			number of items retrieved for the collection (defined in JModelList)
	 *			- list.start			starting index of items for the collection (defined in JModelList)
	 *			- list.ordering			field for ordering the collection
	 *			- list.direction		direction of ordering (asc or desc)
	 *
	 * @since	0.0.1
	 *
	 * @see		JModelList::populateState
	 */
	protected function populateState($ordering = null, $direction = null) 
	{
		// Set the filter.search state
		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		if ($search != '') 
		{
			$this->setState('filter.search', $search);
		}

		// Set the filter.access state
		/*$access = $this->getUserStateFromRequest($this->context . '.filter.access', 'filter_access');
		if ($access != '') 
		{
			$this->setState('filter.access', array($access));
		}*/

		// Set the filter.published state
		$published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published');
		if ($published != '') 
		{
			$this->setState('filter.published', array($published));
		}
		
		// Set the filter.category state
		$category_id = $this->getUserStateFromRequest($this->context . '.filter.catid', 'filter_catid');
		if ($category_id != '') 
		{
			$this->setState('filter.catid', array($category_id));
		}

		$authorId = $this->getUserStateFromRequest($this->context.'.filter.author_id', 'filter_author_id');
		$this->setState('filter.author_id', $authorId);

		// Call populateState from JModelList
		parent::populateState('created', 'asc');
	}

	/**
	 * Method to get a JDatabaseQuery object for retrieving the data set from a database.
	 *
	 * @return	object	A JDatabaseQuery object to retrieve the data set.
	 *
	 * @since	0.0.1
	 *
	 * @see		JModelList::getListQuery
	 */
	protected function getListQuery() 
	{
		// Create a new query object.
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);

		$query->select('e.*');
		$query->from('#__monoslideshow as e');
		
		// Join over the tags.
		$query->select('t.id AS tagid, t.name AS tagname');
		$query->join('LEFT', '#__monoslideshow_tag AS t ON t.id = e.id');
		
		// Join over the categories.
		/*$query->select('c.title AS category_title');
		$query->join('LEFT', '#__categories AS c ON c.id = e.catid');*/
		
		// Join over the categories.
		$query->select('rel.category_id, rel.ordering as ordering, rel.media_category_id');
		$query->join('LEFT', '#__monoslideshow_media_category AS rel ON rel.media_id = e.id');
		
		// Join over the users for the author.
		$query->select('ua.name AS author_name');
		$query->select('ua.email AS author_email');
		$query->join('LEFT', '#__users AS ua ON ua.id = e.author');

		// Join over the users for the checked out user.
		$query->select('uc.name AS editor');
		$query->join('LEFT', '#__users AS uc ON uc.id=e.checked_out');

		// Filter by published state
		if ($published = $this->getState('filter.published')) 
		{
			$query->where('e.published IN (' . implode(',', $published) . ')');
		}
		else
		{
			$query->where('e.published IN (0, 1)');
		}
		
		// Filter by category state
		if ($category_id = $this->getState('filter.catid')) 
		{
			$query->where('rel.category_id IN (' . implode(',', $category_id) . ')');
		}

		// Filter by author
		$authorId = $this->getState('filter.author_id');
		if (is_numeric($authorId)) {
			$type = $this->getState('filter.author_id.include', true) ? '= ' : '<>';
			$query->where('e.author '.$type.(int) $authorId);
		}
		
		// Filter by search in title or alias
		if ($search = $this->getState('filter.search')) 
		{
			
			if (stripos($search, 'id:') === 0) 
			{
				$query->where('e.id = ' . (int)substr($search, 3));
			}
			else
			{
				$search = explode (",", $search);
				foreach ($search as $key => $value)
	  				{
					if ($value)
						{
						$value = trim($value);
						$search = $db->Quote('%' . $db->getEscaped($value, true) . '%');
						$query->where('(title LIKE ' . $search . ') OR (t.name LIKE ' . $search . ')');
						}
					}
			}
		}
		$query->group('e.id');
		// Add the list ordering clause.
		$ordering = $this->getState('list.ordering');
		$direction = $this->getState('list.direction');
		
		
		if ($ordering)
		{
			$query->order($db->getEscaped($ordering) . ' ' . $db->getEscaped($direction));
		}
		if ($ordering == 'modified') 
		{
			$query->order('created ' . $db->getEscaped($direction));
		}

		// return query to JModelList
		return $query;
	}

	/**
	 * Method to get an array of data items.
	 *
	 * @return	mixed	An array of data items on success, false on failure.
	 *
	 * @since	0.0.1
	 *
	 * @see		JModelList::getItems
	 */
	public function getItems() 
	{
		// Get a storage key.
		$store = $this->getStoreId();

		// Try to load the data from internal storage.
		if (!empty($this->cache[$store])) 
		{
			return $this->cache[$store];
		}

		// Get the items from JModelList
		$items = parent::getItems();
		if ($this->getError()) 
		{
			return false;
		}
		
		foreach ($items as $item) 
		{
			// Load tags for each medi
			$db = JFactory::getDbo();
			$query = $db->getQuery(true);

			// Select some fields
			$query->select('name');
			$query->from($db->nameQuote('#__monoslideshow_tag'));
			$query->where('id=' . $item->id);
			$query->order('name');
			$db->setQuery($query);
			$item->tags = $db->loadResultArray();
			if ($db->getErrorNum()) 
			{
				$this->setError($db->getErrorMsg());
				return false;
			}
			$item->categories = $this->getCategories($item->id);
			
		}
		

		// Add the items to the internal cache.
		$this->cache[$store] = $items;
		return $this->cache[$store];
	}
	
	/**
	 * Build a list of authors
	 *
	 * @return	JDatabaseQuery
	 * @since	1.6
	 */
	public function getAuthors() {
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Construct the query
		$query->select('u.id AS value, u.name AS text');
		$query->from('#__users AS u');
		$query->join('INNER', '#__monoslideshow AS c ON c.author = u.id');
		$query->group('u.id');
		$query->order('u.name');

		// Setup the query
		$db->setQuery($query->__toString());

		// Return the result
		return $db->loadObjectList();
	}
	
	/**
	 * Method to fetch the assigned categories
	 *
	 * @access	public
	 * @return	object
	 * @since	1.0
	 */
	function getCategories($id)
	{
		$query = 'SELECT DISTINCT c.id, c.title'
				. ' FROM #__categories AS c'
				. ' LEFT JOIN #__monoslideshow_media_category AS rel ON rel.category_id = c.id'
				. ' WHERE rel.media_id = '.(int)$id
				;
	
		$this->_db->setQuery( $query );

		$this->_cats = $this->_db->loadObjectList();

		return $this->_cats;
	}
	
}
